<template>
    <div class="position-management-container">
        <!-- 顶部标题和操作栏 -->
        <div class="header-section">
            <h2 class="page-title">绩效配置</h2>
            <div class="action-buttons">
                <el-button type="primary" :icon="Plus" @click="addPosition">新增职位</el-button>
                <el-button :icon="Refresh" @click="refreshData">刷新</el-button>
            </div>
        </div>

        <!-- 职位卡片展示 -->
        <div class="position-cards-container">
            <el-card v-for="position in filteredPositions" :key="position.id" class="position-card" shadow="hover">
                <div class="card-content">
                    <div class="card-header">
                        <h3 class="position-title">{{ position.name }}</h3>
                        <div class="position-actions">
                            <div class="action-column">
                                <el-button type="primary" size="small" :icon="User" circle
                                    @click.stop="showEmployees(position)" />
                                <el-button type="warning" size="small" :icon="Edit" circle
                                    @click.stop="editPosition(position)" />
                                <el-button type="info" size="small" :icon="View" circle
                                    @click.stop="viewPerformanceMetrics(position)" />
                                <el-button type="success" size="small" :icon="Setting" circle
                                    @click.stop="showPerformanceSettings(position)" />
                            </div>
                        </div>
                    </div>

                    <div class="position-details">
                        <div class="detail-item">
                            <span class="detail-label">岗位基础值</span>
                            <span class="detail-value">{{ position.baseValue }}</span>
                        </div>

                        <div class="detail-item">
                            <span class="detail-label">岗位基础系数</span>
                            <span class="detail-value">{{ position.baseCoefficient }}</span>
                        </div>

                        <div class="detail-item">
                            <span class="detail-label">岗位系数</span>
                            <span class="detail-value">{{ position.coefficient }}</span>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 已关联员工模态框 -->
        <el-dialog v-model="employeeDialogVisible" :title="`${currentPosition?.name} - 已关联员工 (${employees.length})`"
            width="80%" class="employee-modal">
            <div class="employee-content">
                <div class="employee-toolbar">
                    <el-input v-model="employeeSearch" placeholder="搜索员工" class="employee-search" clearable
                        :prefix-icon="Search" />
                    <el-button type="primary" :icon="Plus" @click="addEmployee">
                        关联员工
                    </el-button>
                </div>

                <div class="employee-grid-container">
                    <div class="employee-grid">
                        <div v-for="employee in filteredEmployees" :key="employee.id" class="employee-card">
                            <el-avatar :size="48" :src="formatAvatarSrc(employee.headerImg)"
                                @error="() => handleAvatarError(employee)">
                                <template #default v-if="!employee.headerImg || employee.headerImg.trim() === ''">
                                    {{ employee.name ? employee.name.charAt(0) : '?' }}
                                </template>
                            </el-avatar>
                            <div class="employee-details">
                                <div class="employee-name">{{ employee.name }}</div>
                                <div class="employee-position-info">
                                    <div class="position-row">
                                        <span class="position-label">权限职位:</span>
                                        <span class="position-value">{{ employee.authorityText }}</span>
                                    </div>
                                    <div class="position-row">
                                        <span class="position-label">绩效职位:</span>
                                        <span class="position-value">{{ employee.positionText }}</span>
                                    </div>
                                </div>
                            </div>
                            <el-button type="danger" size="small" @click.stop="deleteEmployee(employee)">
                                移除
                            </el-button>
                        </div>
                    </div>
                </div>

                <div class="dialog-footer" style="margin-top: 20px; text-align: right;">
                    <el-button @click="employeeDialogVisible = false">关闭</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 可关联员工模态框 -->
        <el-dialog v-model="availableEmployeeDialogVisible" title="关联员工到绩效职位" width="900px"
            class="available-employee-modal">
            <div class="employee-content">
                <div class="employee-toolbar">
                    <el-input v-model="availableEmployeeSearch" placeholder="搜索员工" class="employee-search" clearable
                        :prefix-icon="Search" />
                </div>

                <div class="employee-grid-container">
                    <div class="employee-grid">
                        <div v-for="(employee, index) in filteredAvailableEmployees" :key="employee.id"
                            class="employee-card" :class="{ 'right-column': index % 2 === 1 }"
                            v-show="employee.visible !== false">
                            <el-avatar :size="48" :src="formatAvatarSrc(employee.headerImg)"
                                @error="() => handleAvatarError(employee)">
                                <template #default v-if="!employee.headerImg || employee.headerImg.trim() === ''">
                                    {{ employee.name ? employee.name.charAt(0) : '?' }}
                                </template>
                            </el-avatar>
                            <div class="employee-details">
                                <div class="employee-name">{{ employee.name }}</div>
                                <div class="employee-position-info">
                                    <div class="position-row">
                                        <span class="position-label">权限职位:</span>
                                        <span class="position-value">{{ employee.authorityText }}</span>
                                    </div>
                                    <div class="position-row">
                                        <span class="position-label">绩效职位:</span>
                                        <span class="position-value">{{ employee.positionText }}</span>
                                    </div>
                                </div>
                            </div>
                            <el-checkbox v-model="employee.selected" @change="toggleEmployeeSelection(employee)" />
                        </div>
                    </div>
                </div>

                <div class="dialog-footer">
                    <el-button @click="availableEmployeeDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAssociate">确认关联</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 员工编辑对话框 -->
        <el-dialog v-model="employeeEditDialogVisible"
            :title="`${isEditEmployee ? '编辑' : '新增'}员工 - ${currentPosition?.name}`" width="600px"
            class="employee-edit-dialog">
            <el-form :model="currentEmployee" label-width="100px" label-position="left" :rules="employeeRules"
                ref="employeeForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="currentEmployee.name" placeholder="请输入员工姓名" />
                </el-form-item>

                <el-form-item label="职称" prop="authorityId">
                    <el-select v-model="currentEmployee.authorityId" placeholder="请选择职称" style="width: 100%">
                        <el-option v-for="(value, key) in authorityMap" :key="key" :label="value"
                            :value="parseInt(key)" />
                    </el-select>
                </el-form-item>

                <el-form-item label="岗位" prop="positionId">
                    <el-select v-model="currentEmployee.positionId" placeholder="请选择岗位" style="width: 100%">
                        <el-option v-for="(value, key) in positionMap" :key="key" :label="value"
                            :value="parseInt(key)" />
                    </el-select>
                </el-form-item>

                <el-form-item label="头像" prop="headerImg">
                    <el-input v-model="currentEmployee.headerImg" placeholder="头像base64编码" type="textarea" :rows="2" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="employeeEditDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEmployee">保存</el-button>
            </template>
        </el-dialog>

        <!-- 职位编辑对话框 -->
        <el-dialog v-model="positionDialogVisible" :title="`${isEditPosition ? '编辑' : '新增'}职位`" width="500px"
            class="position-edit-dialog">
            <el-form :model="currentPositionForm" label-width="120px" label-position="left" :rules="positionRules"
                ref="positionForm">
                <el-form-item label="职位名称" prop="name">
                    <el-input v-model="currentPositionForm.name" placeholder="请输入职位名称" />
                </el-form-item>

                <el-form-item label="岗位基础值" prop="baseValue">
                    <el-input-number v-model="currentPositionForm.baseValue" :min="0" controls-position="right" />
                </el-form-item>

                <el-form-item label="岗位基础系数" prop="baseCoefficient">
                    <el-input-number v-model="currentPositionForm.baseCoefficient" :min="0" :step="0.1" :precision="2"
                        controls-position="right" />
                </el-form-item>

                <el-form-item label="岗位系数" prop="coefficient">
                    <el-input-number v-model="currentPositionForm.coefficient" :min="0" :step="0.1" :precision="2"
                        controls-position="right" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="positionDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="savePosition">保存</el-button>
            </template>
        </el-dialog>

        <!-- 绩效设置对话框 -->
        <el-dialog v-model="performanceDialogVisible" title="设置绩效类型区间阈值" width="75%" class="performance-dialog">
            <div class="performance-toolbar">
                <div class="toolbar-left">
                    <el-input v-model="performanceSearch" placeholder="搜索绩效类型" clearable style="width: 300px" />
                    <el-tag class="toolbar-chip" type="success" effect="light">共 {{ currentPerformanceMetrics.length }} 类</el-tag>
                </div>
                <div class="toolbar-right">
                    <el-button size="small" :icon="Refresh" @click="showPerformanceSettings(currentPosition)">重置默认</el-button>
                </div>
            </div>
            <el-table :data="groupedPerformanceMetrics.filter(g => {
                if (!performanceSearch) return true
                const searchTerm = performanceSearch.toLowerCase()
                return (
                    g[0]?.name?.toLowerCase().includes(searchTerm) ||
                    (g[1]?.name?.toLowerCase().includes(searchTerm))
                )
            })" border stripe :resizable="false" style="width: 100%" height="500px">
                <el-table-column label="绩效类型" min-width="220" :resizable="false">
                    <template #default="{ row }">
                        <div>{{ row[0]?.name }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="最小值" min-width="120" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <el-input-number v-model="row[0].minValue" size="small" style="width: 100px"
                            @change="handlePerformanceChange(row[0])" />
                    </template>
                </el-table-column>
                <el-table-column label="最大值" min-width="120" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <el-input-number v-model="row[0].maxValue" size="small" style="width: 100px"
                            @change="handlePerformanceChange(row[0])" />
                    </template>
                </el-table-column>
                <el-table-column label="分数阈值" min-width="120" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <el-input-number v-model="row[0].scoreThreshold" size="small" style="width: 100px"
                            @change="handlePerformanceChange(row[0])" />
                    </template>
                </el-table-column>

                <el-table-column label="绩效类型" min-width="220" :resizable="false">
                    <template #default="{ row }">
                        <div>{{ row[1]?.name }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="最小值" min-width="120" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <el-input-number v-if="row[1]" v-model="row[1].minValue" size="small" style="width: 100px"
                            @change="handlePerformanceChange(row[1])" />
                    </template>
                </el-table-column>
                <el-table-column label="最大值" min-width="120" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <el-input-number v-if="row[1]" v-model="row[1].maxValue" size="small" style="width: 100px"
                            @change="handlePerformanceChange(row[1])" />
                    </template>
                </el-table-column>
                <el-table-column label="分数阈值" min-width="120" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <el-input-number v-if="row[1]" v-model="row[1].scoreThreshold" size="small" style="width: 100px"
                            @change="handlePerformanceChange(row[1])" />
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <el-button @click="performanceDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>

        <!-- 查看绩效对话框 -->
        <el-dialog v-model="viewPerformanceDialogVisible" title="查看绩效类型区间" width="75%" class="performance-dialog">
            <div class="performance-toolbar">
                <el-input v-model="performanceSearch" placeholder="搜索绩效类型" clearable style="width: 300px" />
            </div>
            <el-table :data="groupedViewingMetrics.filter(g => {
                if (!performanceSearch) return true
                const searchTerm = performanceSearch.toLowerCase()
                return (
                    g[0]?.name?.toLowerCase().includes(searchTerm) ||
                    (g[1]?.name?.toLowerCase().includes(searchTerm))
                )
            })" border stripe :resizable="false" style="width: 100%" height="500px">
                <el-table-column label="绩效类型" min-width="260" :resizable="false">
                    <template #default="{ row }">
                        <div>{{ row[0]?.name }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="最小值" min-width="140" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <span>{{ row[0]?.minValue }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="最大值" min-width="140" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <span>{{ row[0]?.maxValue }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="分数阈值" min-width="140" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <span>{{ row[0]?.scoreThreshold }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="绩效类型" min-width="260" :resizable="false">
                    <template #default="{ row }">
                        <div>{{ row[1]?.name }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="最小值" min-width="140" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <span v-if="row[1]">{{ row[1].minValue }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="最大值" min-width="140" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <span v-if="row[1]">{{ row[1].maxValue }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="分数阈值" min-width="140" :resizable="false" align="center" header-align="center">
                    <template #default="{ row }">
                        <span v-if="row[1]">{{ row[1].scoreThreshold }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <el-button type="primary" @click="viewPerformanceDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {
    Plus,
    Refresh,
    Search,
    User,
    Edit,
    Setting,
    View
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    GetPositionList,// 获取所有的职位
    GetPositionTypeListByPositionId,// 根据职位id获取绩效类型
    AddPosition,// 新增职位
    UpdatePositionById,// 根据id修改职位
    UpdatePositionType,// 根据id修改绩效类型
    GetPositionUser,// 获取参与绩效计算的用户
    GetPositionUserByPositionId,// 获取已关联职位的用户
    AssPositionUser,// 绩效职位关联用户
} from "@/api/newDemands/index";

// 职位数据
const positions = ref([])

// 搜索功能
const searchQuery = ref('')
const filteredPositions = computed(() => {
    if (!searchQuery.value) return positions.value
    return positions.value.filter(position =>
        position.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
})

// 职称映射
const authorityMap = {
    111: '测试管理者',
    222: '运维人员',
    333: '项目经理管理者',
    444: '项目经理',
    555: '技术负责人',
    666: '测试人员',
    777: '研发人员',
    888: '超级管理员',
    999: '公司管理者'
}

const positionMap = {
    1: '特殊',
    2: 'JAVA核心',
    3: '前端核心',
    4: '测试核心',
    5: '项目核心',
    6: '产品',
    7: '技术负责人',
    8: 'java',
    9: '前端',
    10: '测试',
    11: '运维',
    12: '项目经理'
}

// 获取职称显示文本
const getAuthorityText = (authorityId) => {
    return authorityMap[authorityId] || '未知职称'
}

// 获取岗位显示文本
const getPositionText = (positionId) => {
    return positionMap[positionId] || '未关联绩效职位'
}

// 员工模态框相关状态
const employeeDialogVisible = ref(false) // 已关联员工模态框
const availableEmployeeDialogVisible = ref(false) // 可关联员工模态框
const employeeEditDialogVisible = ref(false)
const currentPosition = ref(null)
const employees = ref([]) // 已关联员工列表
const availableEmployees = ref([]) // 可关联员工列表
const employeeSearch = ref('')
const availableEmployeeSearch = ref('')
const employeeLoading = ref(false)
const availableEmployeeLoading = ref(false)

// 分组员工数据
const groupedEmployees = computed(() => {
    const filtered = filteredEmployees.value
    const result = []
    for (let i = 0; i < filtered.length; i += 2) {
        result.push(filtered.slice(i, i + 2))
    }
    return result
})

// 合并单元格方法
const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex === 0 && !row[0]) {
        return [0, 0]
    }
    if (columnIndex === 1 && !row[1]) {
        return [0, 0]
    }
    return {
        rowspan: 1,
        colspan: 1
    }
}


// 过滤员工数据
const filteredEmployees = computed(() => {
    if (!employeeSearch.value) return employees.value
    return employees.value.filter(employee =>
        employee.name.toLowerCase().includes(employeeSearch.value.toLowerCase()) ||
        employee.phone.includes(employeeSearch.value)
    )
})

// 过滤可关联员工数据
const filteredAvailableEmployees = computed(() => {
    if (!availableEmployeeSearch.value) return availableEmployees.value
    const searchTerm = availableEmployeeSearch.value.toLowerCase()
    return availableEmployees.value.filter(employee => {
        return (
            employee.name.toLowerCase().includes(searchTerm) ||
            (employee.phone && employee.phone.includes(searchTerm)) ||
            (employee.authorityText && employee.authorityText.toLowerCase().includes(searchTerm)) ||
            (employee.positionText && employee.positionText.toLowerCase().includes(searchTerm))
        )
    })
})

// 选中的员工
const selectedEmployees = ref([])
const employeeTable = ref(null)
const availableEmployeeTable = ref(null)

// 处理选择变化
const handleSelectionChange = (selection) => {
    selectedEmployees.value = selection
}

// 处理可关联员工选择变化
const handleAvailableSelectionChange = (selection) => {
    selectedEmployees.value = selection
}

// 确认关联员工
const confirmAssociate = async () => {
    // 获取所有选中的员工（包括已关联和新增的）
    const allSelectedEmployees = availableEmployees.value.filter(e => e.selected);

    if (allSelectedEmployees.length === 0) {
        ElMessage.warning('请至少选择一个员工')
        return
    }

    const loading = ElLoading.service({
        lock: true,
        text: '正在关联员工...',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
        // 调用API关联员工到当前岗位
        const { data } = await AssPositionUser({
            id: currentPosition.value.id,
            uuids: allSelectedEmployees.map(e => e.id)
        });

        if (data.code !== 200) {
            throw new Error(data.msg || '关联员工失败');
        }

        ElMessage.success(`成功关联 ${allSelectedEmployees.length} 个员工到 ${currentPosition.value.name} 岗位`)

        // 关闭模态框
        availableEmployeeDialogVisible.value = false

        // 清空选择
        selectedEmployees.value = []
        if (availableEmployeeTable.value) {
            availableEmployeeTable.value.clearSelection()
        }

        // 重新加载已关联员工列表
        if (currentPosition.value) {
            await showEmployees(currentPosition.value)
        }
    } catch (error) {
        console.error('关联员工失败:', error)
        ElMessage.error(error.message || '关联员工失败')
    }
}

// 职位编辑相关状态
const positionDialogVisible = ref(false)
const currentPositionForm = ref({
    id: null,
    name: '',
    baseValue: 8000,
    baseCoefficient: 1.0,
    coefficient: 1.0
})
const isEditPosition = ref(false)
const positionForm = ref(null)

// 绩效相关状态
const performanceDialogVisible = ref(false)
const viewPerformanceDialogVisible = ref(false)
const currentPerformanceMetrics = ref([])
const viewingPerformanceMetrics = ref([])
const performanceSearch = ref('')

// 分组绩效指标
const groupedPerformanceMetrics = computed(() => {
    // 先过滤单个绩效类型
    const filtered = currentPerformanceMetrics.value.filter(item => {
        if (!performanceSearch.value) return true
        const searchTerm = performanceSearch.value.toLowerCase()
        return item.name.toLowerCase().includes(searchTerm)
    })

    // 然后分组
    const result = []
    for (let i = 0; i < filtered.length; i += 2) {
        result.push(filtered.slice(i, i + 2))
    }
    return result
})

// 分组查看指标
const groupedViewingMetrics = computed(() => {
    // 先过滤单个绩效类型
    const filtered = viewingPerformanceMetrics.value.filter(item => {
        if (!performanceSearch.value) return true
        const searchTerm = performanceSearch.value.toLowerCase()
        return item.name.toLowerCase().includes(searchTerm)
    })

    // 然后分组
    const result = []
    for (let i = 0; i < filtered.length; i += 2) {
        result.push(filtered.slice(i, i + 2))
    }
    return result
})

// 显示绩效设置模态框
const showPerformanceSettings = async (position) => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在加载绩效设置...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    try {
        const { data } = await GetPositionTypeListByPositionId(position.id)
        if (data.code === 200) {
            // 转换API返回的数据结构为前端需要的格式
            currentPerformanceMetrics.value = data.data.map(item => ({
                id: item.ID,
                name: item.userPositionName,
                minValue: item.minPerformance,
                maxValue: item.maxPerformance,
                scoreThreshold: item.scoreThreshold
            }))
            currentPosition.value = position
            performanceDialogVisible.value = true
        } else {
            ElMessage.error(data.msg || '获取绩效类型失败')
        }
    } catch (error) {
        console.error('获取绩效类型出错:', error)
        ElMessage.error('获取绩效类型出错')
    } finally {
        loading.close()
    }
}

// 查看绩效指标
const viewPerformanceMetrics = async (position) => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在加载绩效数据...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    try {
        const { data } = await GetPositionTypeListByPositionId(position.id)
        if (data.code === 200) {
            // 转换API返回的数据结构为前端需要的格式
            viewingPerformanceMetrics.value = data.data.map(item => ({
                id: item.ID,
                name: item.userPositionName,
                minValue: item.minPerformance,
                maxValue: item.maxPerformance,
                scoreThreshold: item.scoreThreshold
            }))
            viewPerformanceDialogVisible.value = true
        } else {
            ElMessage.error(data.msg || '获取绩效类型失败')
        }
    } catch (error) {
        console.error('获取绩效类型出错:', error)
        ElMessage.error('获取绩效类型出错')
    } finally {
        loading.close()
    }
}

// 处理绩效区间变化
const handlePerformanceChange = async (metric) => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在更新绩效区间...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    try {
        const { data } = await UpdatePositionType({
            id: metric.id,
            maxPerformance: metric.maxValue,
            minPerformance: metric.minValue,
            scoreThreshold: metric.scoreThreshold
        });

        if (data.code === 200) {
            ElMessage.success('绩效区间更新成功');
        } else {
            ElMessage.error(data.msg || '绩效区间更新失败');
        }
    } catch (error) {
        console.error('更新绩效区间出错:', error);
        ElMessage.error('更新绩效区间出错');
    } finally {
        loading.close()
    }
}

// 保存绩效设置 (保留但不再使用)
const savePerformanceMetrics = async () => {
    // 这个方法现在不再需要，但保留以防其他地方调用
}

// 职位表单验证规则
const positionRules = {
    name: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
    baseValue: [{ required: true, message: '请输入岗位基础值', trigger: 'blur' }],
    baseCoefficient: [{ required: true, message: '请输入岗位基础系数', trigger: 'blur' }],
    coefficient: [{ required: true, message: '请输入岗位系数', trigger: 'blur' }]
}

// 显示员工模态框
const showEmployees = async (position) => {
    currentPosition.value = position
    employeeLoading.value = true
    const loading = ElLoading.service({
        lock: true,
        text: '正在加载员工数据...',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
        const { data } = await GetPositionUserByPositionId(position.id)
        if (data.code === 200) {
            employees.value = data.data.map(user => ({
                id: user.uuid,
                name: user.nickName,
                authorityId: user.authorityId,
                positionId: user.positionId,
                authorityText: getAuthorityText(user.authorityId),
                positionText: getPositionText(user.positionId),
                headerImg: user.headerImg
            }))
            employeeDialogVisible.value = true
            ElMessage.success(data.msg || '获取员工列表成功')
        } else {
            ElMessage.error(data.msg || '获取员工列表失败')
            employees.value = []
        }
    } catch (error) {
        console.error('获取员工列表出错:', error)
        ElMessage.error('获取员工列表出错')
        employees.value = []
    } finally {
        loading.close()
        employeeLoading.value = false
    }
}

// 获取可关联员工
const getAvailableEmployees = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在加载可关联员工...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    try {
        availableEmployeeLoading.value = true
        // 获取所有可关联员工
        const { data: allEmployees } = await GetPositionUser(currentPosition.value.id)
        // 获取已关联员工
        const { data: associatedEmployees } = await GetPositionUserByPositionId(currentPosition.value.id)

        if (allEmployees.code === 200 && associatedEmployees.code === 200) {
            // 获取已关联员工的ID集合
            const associatedIds = new Set(associatedEmployees.data.map(e => e.uuid))

            availableEmployees.value = allEmployees.data.map(user => {
                const isSelected = associatedIds.has(user.uuid);
                if (isSelected && !selectedEmployees.value.some(e => e.id === user.uuid)) {
                    selectedEmployees.value.push({
                        id: user.uuid,
                        name: user.nickName,
                        authorityId: user.authorityId,
                        positionId: user.positionId,
                        authorityText: getAuthorityText(user.authorityId),
                        positionText: getPositionText(user.positionId),
                        headerImg: user.headerImg
                    });
                }
                return {
                    id: user.uuid,
                    name: user.nickName,
                    authorityId: user.authorityId,
                    positionId: user.positionId,
                    authorityText: getAuthorityText(user.authorityId),
                    positionText: getPositionText(user.positionId),
                    headerImg: user.headerImg,
                    selected: isSelected
                };
            });
            return true
        } else {
            ElMessage.error(allEmployees.msg || associatedEmployees.msg || '获取可关联员工失败')
            availableEmployees.value = []
            return false
        }
    } catch (error) {
        console.error('获取可关联员工出错:', error)
        ElMessage.error('获取可关联员工出错')
        availableEmployees.value = []
        return false
    } finally {
        loading.close()
        availableEmployeeLoading.value = false
    }
}

// 打开关联员工模态框
const addEmployee = async () => {
    if (!currentPosition.value) return
    availableEmployeeSearch.value = '' // 重置搜索框
    availableEmployeeLoading.value = true // 开启加载状态
    try {
        const success = await getAvailableEmployees()
        if (success) {
            availableEmployeeDialogVisible.value = true
        }
    } finally {
        availableEmployeeLoading.value = false // 关闭加载状态
    }
}

// 编辑员工
const editEmployee = (employee) => {
    isEditEmployee.value = true
    currentEmployee.value = {
        ...employee,
        authorityText: undefined,
        positionText: undefined
    }
    employeeEditDialogVisible.value = true
}

// 保存员工信息
const saveEmployee = async () => {
    try {
        await employeeForm.value.validate()

        if (isEditEmployee.value) {
            // 更新员工
            const index = employees.value.findIndex(e => e.id === currentEmployee.value.id)
            if (index !== -1) {
                employees.value[index] = {
                    ...currentEmployee.value,
                    authorityText: getAuthorityText(currentEmployee.value.authorityId),
                    positionText: getPositionText(currentEmployee.value.positionId)
                }
                ElMessage.success('员工信息更新成功')
            }
        } else {
            // 新增员工
            employees.value.push({
                ...currentEmployee.value,
                id: currentEmployee.value.id || Date.now().toString(),
                authorityText: getAuthorityText(currentEmployee.value.authorityId),
                positionText: getPositionText(currentEmployee.value.positionId)
            })
            ElMessage.success('员工添加成功')
        }

        employeeEditDialogVisible.value = false
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

// 删除员工
const deleteEmployee = async (employee) => {
    try {
        await ElMessageBox.confirm(
            `确定要从该岗位移除员工 "${employee.name}" 吗?`,
            '移除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        // 这里调用API移除员工
        // 示例: await RemoveEmployeeFromPosition(currentPosition.value.id, employee.id)

        employees.value = employees.value.filter(e => e.id !== employee.id)
        ElMessage.success('员工移除成功')

        // 重新加载员工列表
        if (currentPosition.value) {
            await showEmployees(currentPosition.value)
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('移除员工出错:', error)
            ElMessage.error('移除员工失败')
        }
    }
}

// 编辑职位
const editPosition = (position) => {
    isEditPosition.value = true
    currentPositionForm.value = {
        id: position.id,
        name: position.name,
        baseValue: position.baseValue,
        baseCoefficient: position.baseCoefficient,
        coefficient: position.coefficient
    }
    positionDialogVisible.value = true
}

// 新增职位
const addPosition = () => {
    isEditPosition.value = false
    currentPositionForm.value = {
        id: null,
        name: '',
        baseValue: 8000,
        baseCoefficient: 1.0,
        coefficient: 1.0
    }
    positionDialogVisible.value = true
}

// 保存职位信息
const savePosition = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在保存职位信息...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    try {
        await positionForm.value.validate()

        if (isEditPosition.value) {
            // 更新职位 - 调用API
            const { data } = await UpdatePositionById({
                id: currentPositionForm.value.id,
                position: currentPositionForm.value.name,
                jobXs: currentPositionForm.value.coefficient,
                jobXsjc: currentPositionForm.value.baseCoefficient,
                basePerformance: currentPositionForm.value.baseValue
            })
            loading.close()
            if (data.code === 200) {
                const index = positions.value.findIndex(p => p.id === currentPositionForm.value.id)
                if (index !== -1) {
                    positions.value[index] = {
                        id: data.data.ID,
                        name: data.data.position,
                        baseValue: data.data.basePerformance,
                        baseCoefficient: data.data.jobXsjc,
                        coefficient: data.data.jobXs,
                        performanceMetrics: positions.value[index].performanceMetrics
                    }
                }
                ElMessage.success('职位信息更新成功')
                await loadPositions() // 重新获取最新数据
            } else {
                ElMessage.error(data.msg || '更新职位失败')
            }
        } else {
            // 新增职位 - 调用API
            const { data } = await AddPosition({
                position: currentPositionForm.value.name,
                jobXs: currentPositionForm.value.coefficient,
                jobXsjc: currentPositionForm.value.baseCoefficient,
                basePerformance: currentPositionForm.value.baseValue
            })

            if (data.code === 200) {
                positions.value.push({
                    id: data.data.ID,
                    name: data.data.position,
                    baseValue: data.data.basePerformance,
                    baseCoefficient: data.data.jobXsjc,
                    coefficient: data.data.jobXs,
                    performanceMetrics: []
                })
                ElMessage.success('职位添加成功')
            } else {
                ElMessage.error(data.msg || '添加职位失败')
            }
        }

        positionDialogVisible.value = false
    } catch (error) {
        console.error('保存职位出错:', error)
        if (error.response) {
            ElMessage.error(error.response.data.msg || '保存职位出错')
        } else {
            ElMessage.error('保存职位出错')
        }
    }
}

// 处理职位信息变更
const handlePositionChange = (position) => {
    ElMessage.success(`职位 "${position.name}" 信息已更新`)
    // 这里可以添加保存到后端的逻辑
}

// 加载职位数据
const loadPositions = async () => {
    const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在加载职位数据...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    try {
        loading.value = true
        const { data } = await GetPositionList()
        loadingInstance.close()
        if (data.code === 200) {
            positions.value = data.data.map(item => ({
                id: item.ID,
                name: item.position,
                baseValue: item.basePerformance,
                baseCoefficient: item.jobXsjc,
                coefficient: item.jobXs,
                performanceMetrics: []
            }))
        } else {
            ElMessage.error(data.msg || '获取职位列表失败')
        }
    } catch (error) {
        ElMessage.error('获取职位列表出错')
    } finally {
        loading.value = false
    }
}

// 刷新数据
const refreshData = async () => {
    await loadPositions()
}

// 格式化头像源
const formatAvatarSrc = (headerImg) => {
    if (!headerImg || headerImg.trim() === '') return ''

    // 已经是完整data URL
    if (headerImg.startsWith('data:image')) return headerImg

    // 假设是base64编码
    if (!headerImg.startsWith('http')) {
        return `data:image/png;base64,${headerImg}`
    }

    // 普通URL
    return headerImg
}

// 分组可关联员工数据
const groupedAvailableEmployees = computed(() => {
    // 先处理选中状态
    const processedEmployees = filteredAvailableEmployees.value.map(emp => ({
        ...emp,
        selected: selectedEmployees.value.some(sel => sel.id === emp.id)
    }))

    const result = []
    for (let i = 0; i < processedEmployees.length; i += 2) {
        result.push(processedEmployees.slice(i, i + 2))
    }
    return result
})

// 切换员工选择状态
const toggleEmployeeSelection = (employee) => {
    if (employee.selected) {
        // 避免重复添加
        if (!selectedEmployees.value.some(e => e.id === employee.id)) {
            selectedEmployees.value.push(employee)
        }
    } else {
        selectedEmployees.value = selectedEmployees.value.filter(e => e.id !== employee.id)
    }
}

// 处理头像加载错误
const handleAvatarError = (row) => {
    console.error(`头像加载失败: ${row.name}`)
    row.headerImg = '' // 清空错误头像
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 从后端加载数据
const loading = ref(true)
onMounted(async () => {
    await loadPositions()
})
</script>

<style scoped>
.position-management-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

/* 绩效设置对话框优化 */
.performance-dialog {
    /* 可调整的主题色，便于统一风格 */
    --brand-primary: #1677ff;
    --brand-success: #34c759;
    --brand-warning: #faad14;
    --brand-bg-soft: #f6f9ff;
}
.performance-dialog :deep(.el-dialog) {
    border-radius: 12px;
    box-shadow: 0 16px 40px rgba(0, 0, 0, 0.18);
    max-width: 1200px; /* 控制最大宽度，更贴近视觉黄金比例 */
}

.performance-dialog :deep(.el-dialog__header) {
    padding: 16px 18px;
    border-bottom: 1px solid #ebeef5;
    background: linear-gradient(135deg, #f0f7ff 0%, #ffffff 60%);
}

.performance-dialog :deep(.el-dialog__body) {
    padding: 12px 18px 10px 18px;
    background: linear-gradient(180deg, #ffffff 0%, #fcfcfd 100%);
}

.performance-toolbar {
    position: sticky;
    top: 0;
    z-index: 3;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0 12px 0;
    margin-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
}

.performance-toolbar .toolbar-left {
    display: flex;
    gap: 10px;
    align-items: center;
}

.performance-toolbar .toolbar-right {
    display: flex;
    gap: 8px;
}

.performance-toolbar .toolbar-chip {
    --tw-shadow: 0 1px 3px rgba(0,0,0,0.08);
    box-shadow: var(--tw-shadow);
    border-radius: 999px;
    border-color: rgba(22, 119, 255, 0.25);
}

.performance-toolbar .toolbar-meta {
    color: #909399;
    font-size: 12px;
}

.performance-dialog :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 52px; /* below toolbar */
    z-index: 2;
    box-shadow: 0 2px 0 rgba(0, 0, 0, 0.02);
}

.performance-dialog :deep(.el-table__header-wrapper th) {
    background-color: #f8f9fa;
    color: #606266;
    text-align: center;
    font-weight: 600;
}

/* 紧凑表格 + 居中对齐 */
.performance-dialog :deep(.el-table .cell) {
    padding: 8px 6px !important;
    text-align: center;
    overflow: visible; /* 避免输入框后出现省略号 */
    text-overflow: unset;
    white-space: nowrap;
}

/* 让表格自动充满容器，避免右侧空白 */
.performance-dialog :deep(.el-table) {
    width: 100%;
}

/* 彻底移除可能由样式注入的省略号伪元素 */
.performance-dialog :deep(.el-table__cell .cell::after),
.performance-dialog :deep(.el-table__cell::after) {
    content: none !important;
}

.performance-dialog :deep(.el-table__row td) {
    vertical-align: middle;
    transition: background-color .15s ease;
}

/* 斑马纹与 Hover 效果 */
.performance-dialog :deep(.el-table__body tr:nth-child(odd) td) {
    background: #fafafa;
}
.performance-dialog :deep(.el-table__body tr:hover td) {
    background: #f2f6fc !important;
}

/* 数字输入尺寸与对齐优化 */
.performance-dialog :deep(.el-input-number--small) {
    height: 28px;
}
.performance-dialog :deep(.el-input-number) {
    width: 110px; /* 稍微加宽，避免显示省略号 */
}
.performance-dialog :deep(.el-input-number .el-input__inner) {
    text-align: center;
    padding: 0 6px;
}
.performance-dialog :deep(.el-input-number .el-input__inner:focus) {
    box-shadow: 0 0 0 2px rgba(22, 119, 255, .15);
    border-color: var(--brand-primary);
}
.performance-dialog :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 2px rgba(22, 119, 255, .15) inset;
}
.performance-dialog :deep(.el-input__wrapper:hover) {
    border-color: var(--brand-primary);
}
.performance-dialog :deep(.el-button) {
    transition: all .15s ease;
}
.performance-dialog :deep(.el-button:hover) {
    filter: brightness(1.02);
}
.performance-dialog :deep(.el-button--primary) {
    background: var(--brand-primary);
    border-color: var(--brand-primary);
}
.performance-dialog :deep(.el-tag--success) {
    color: #15a04a;
    background-color: rgba(52, 199, 89, 0.12);
}

/* 底部区域优化 */
.performance-dialog :deep(.el-dialog__footer) {
    padding: 10px 18px 14px 18px;
    border-top: 1px solid #ebeef5;
    background: #fff;
}

/* 自定义滚动条（仅影响该对话框内部） */
.performance-dialog :deep(.el-dialog__body)::-webkit-scrollbar,
.performance-dialog :deep(.el-table__body-wrapper)::-webkit-scrollbar {
    height: 8px;
    width: 8px;
}
.performance-dialog :deep(.el-dialog__body)::-webkit-scrollbar-thumb,
.performance-dialog :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
    background: rgba(0,0,0,0.15);
    border-radius: 8px;
}
.performance-dialog :deep(.el-dialog__body)::-webkit-scrollbar-thumb:hover,
.performance-dialog :deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
    background: rgba(0,0,0,0.25);
}

.position-management-container .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.position-management-container .header-section .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
}

.position-management-container .header-section .action-buttons {
    display: flex;
    gap: 10px;
}

.position-management-container .position-cards-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.position-management-container .position-cards-container .position-card {
    border-radius: 8px;
    transition: transform 0.3s, box-shadow 0.3s;
}

.position-management-container .position-cards-container .position-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.position-management-container .position-cards-container .position-card .card-content {
    padding: 15px;
}

.position-management-container .position-cards-container .position-card .card-content .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;
}

.position-management-container .position-cards-container .position-card .card-content .card-header .position-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0;
}

.position-management-container .position-cards-container .position-card .card-content .card-header .position-actions {
    display: flex;
    gap: 8px;
}

.position-management-container .position-cards-container .position-card .card-content .position-details .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.position-management-container .position-cards-container .position-card .card-content .position-details .detail-item .detail-label {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
}

.position-management-container .position-cards-container .position-card .card-content .position-details .detail-item .detail-value {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
}

.position-management-container .employee-modal .el-dialog__body {
    padding: 20px;
}

.position-management-container .employee-modal .employee-content .employee-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.position-management-container .employee-modal .employee-content .employee-toolbar .employee-search {
    width: 200px;
}

.position-management-container .employee-modal .employee-content .salary-text {
    font-weight: 500;
    color: #f56c6c;
}

.position-management-container .employee-modal .el-dialog {
    max-width: 1200px;
}

.position-management-container .employee-modal .employee-cell {
    display: flex;
    align-items: center;
    padding: 10px;
    gap: 15px;
}

.position-management-container .employee-modal .employee-cell .employee-info {
    flex: 1;
}

.position-management-container .employee-modal .employee-cell .employee-info .employee-name {
    font-weight: 500;
    margin-bottom: 4px;
}

.position-management-container .employee-modal .employee-cell .employee-info .employee-position {
    font-size: 12px;
    color: #909399;
}

.employee-position-info {
    font-size: 12px;
    color: #606266;
    margin-top: 4px;
}

.position-row {
    display: flex;
    line-height: 1.4;
}

.position-label {
    color: #909399;
    margin-right: 6px;
    min-width: 60px;
}

.position-value {
    color: #606266;
    font-weight: 500;
}

.position-management-container .employee-modal .el-table__body tr:hover>td {
    background-color: transparent !important;
}

.position-management-container .employee-modal .el-table__body .cell {
    padding: 0 !important;
}

.position-management-container .employee-edit-dialog .el-dialog__body,
.position-management-container .position-edit-dialog .el-dialog__body {
    padding: 20px 25px;
}

.position-management-container .employee-edit-dialog .salary-input,
.position-management-container .position-edit-dialog .salary-input {
    width: 100%;
}

.position-management-container .performance-collapse {
    margin-top: 15px;
}

.position-management-container .performance-collapse .performance-metrics {
    max-height: 300px;
    overflow-y: auto;
}

.position-management-container .performance-collapse .performance-metrics .metric-item {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid #ebeef5;
}

.position-management-container .performance-collapse .performance-metrics .metric-item .metric-name {
    font-weight: 500;
    color: #303133;
}

.position-management-container .performance-collapse .performance-metrics .metric-item .metric-values {
    display: flex;
    gap: 15px;
}

.position-management-container .performance-collapse .performance-metrics .metric-item .metric-values span {
    color: #606266;
}

.position-management-container .performance-toolbar {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
}

.position-management-container .position-edit-dialog .el-table {
    margin-top: 10px;
}

.position-management-container .position-edit-dialog .el-table .el-input-number {
    width: 100px;
}

.position-management-container .card-header {
    display: flex;
    flex-direction: column;
    gap: 16px;
    margin-bottom: 15px;
}

.position-management-container .card-header .position-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.position-management-container .card-header .position-actions {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
}

.position-management-container .card-header .position-actions .action-column .el-button {
    width: 32px;
    height: 32px;
}

/* 关联员工模态框优化样式 */
.employee-modal .el-dialog {
    border-radius: 8px;
    max-width: 1000px;
}

.employee-modal .el-dialog__header {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;
}

.employee-modal .el-dialog__title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.employee-modal .el-dialog__body {
    padding: 20px;
}

/* 工具栏样式优化 */
.employee-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
}

.employee-search {
    width: 300px;
}

/* 表格样式优化 */
.employee-grid-container {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

.employee-modal .el-table {
    border-radius: 6px;
    border: 1px solid #ebeef5;
}

.employee-modal .el-table__header th {
    background-color: #f8f9fa;
    font-weight: 600;
}

.employee-modal .el-table .cell {
    padding: 0 12px;
}

/* 员工卡片样式优化 */
.employee-cell {
    display: flex;
    align-items: center;
    padding: 10px;
    gap: 15px;
}

.employee-cell .el-avatar {
    flex-shrink: 0;
}

.employee-info {
    flex: 1;
    min-width: 0;
}

.employee-name {
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.employee-position {
    font-size: 12px;
    color: #909399;
}

/* 底部按钮区域优化 */
.dialog-footer {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
    text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .employee-modal .el-dialog {
        width: 90% !important;
    }

    .employee-toolbar {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .employee-search {
        width: 100%;
    }
}

/* 关联员工模态框优化样式 */
.available-employee-modal .el-dialog {
    border-radius: 8px;
    max-width: 900px;
}

.available-employee-modal .el-dialog__header {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
}

.available-employee-modal .el-dialog__title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.available-employee-modal .el-dialog__body {
    padding: 15px 20px;
}

/* 表格样式优化 */
.available-employee-table {
    width: 100%;
    border-radius: 6px;
}

.available-employee-table .el-table__header-wrapper th {
    background-color: #f8f9fa;
    font-weight: 600;
    color: #606266;
}

.available-employee-table .el-table__row {
    height: 60px;
}

/* 员工信息单元格样式 */
.employee-info-cell {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 0;
}

.employee-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    color: #409eff;
}

.employee-details {
    display: flex;
    flex-direction: column;
}

.employee-name {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 2px;
}

.employee-title {
    font-size: 12px;
    color: #909399;
}

/* 选择列样式 */
.available-employee-table .selection-column {
    padding-right: 10px;
}

/* 底部按钮区域优化 */
.available-employee-footer {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
    text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .available-employee-modal .el-dialog {
        width: 95% !important;
    }

    .employee-info-cell {
        flex-direction: column;
        align-items: flex-start;
        gap: 6px;
    }

    .employee-details {
        margin-left: 0;
    }
}

/* 两列表格样式 */
.two-column-table .el-table__body-wrapper {
    overflow-x: hidden;
}

.two-column-table .el-table__body tr:hover>td {
    background-color: transparent !important;
}

.two-column-table .el-table__body .cell {
    padding: 8px !important;
}

.two-column-table .employee-cell {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px;
    height: 100%;
}

.two-column-table .employee-cell .el-avatar {
    flex-shrink: 0;
}

.two-column-table .employee-cell .employee-info {
    flex: 1;
    min-width: 0;
}

.two-column-table .employee-cell .employee-name {
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.two-column-table .employee-cell .employee-position {
    font-size: 12px;
    color: #909399;
}

.two-column-table .employee-cell .el-checkbox {
    margin-left: auto;
    margin-right: 8px;
}

/* 确保表格单元格有足够空间 */
.two-column-table .el-table__body td {
    padding: 0 !important;
    height: 72px;
    vertical-align: top;
}

/* 解决边框重叠问题 */
.two-column-table .el-table--border .el-table__cell {
    border-right: 1px solid var(--el-table-border-color);
}

.available-employee-modal {
    --employee-card-gap: 16px;
}

.employee-grid-container {
    max-height: 60vh;
    overflow-y: auto;
    margin-top: 16px;
}

.employee-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: var(--employee-card-gap);
    padding: 4px;
}

.employee-card {
    display: flex;
    align-items: center;
    padding: 12px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    transition: all 0.2s;
    gap: 12px;
}

.employee-card:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.employee-details {
    flex: 1;
    min-width: 0;
}

.employee-name {
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.employee-position {
    font-size: 12px;
    color: #909399;
}

.employee-card .el-checkbox {
    margin-left: auto;
}

.dialog-footer {
    margin-top: 20px;
    text-align: right;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .employee-grid {
        grid-template-columns: 1fr;
    }
}
</style>